package com.GLM.Viewer.MyNews;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.StateListDrawable;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.GLM.Constants.Constant;
import com.GLM.Entity.UnReadMeetMsg;
import com.GLM.Entity.UnReadRIVMsg;
import com.GLM.Entity.UnReadRingMsg;
import com.GLM.Entity.UnReadSms;
import com.GLM.Tools.DB.DAO.UserInfoDAO;
import com.GLM.Tools.Utils.ViewsUtil;
import com.GLM.Tools.Utils.JSON.JSONResponse;
import com.GLM.Tools.Utils.JSON.JSONUtil;
import com.GLM.Tools.Utils.JSON.JSONResponse.Status;
import com.GLM.Viewer.R;
import com.GLM.Viewer.Circle.CreateNewCircleMyFriendsViewActivity;
import com.GLM.Viewer.Users.UserSettingActivity;

public class NewsActivity extends Activity implements OnClickListener, OnPageChangeListener {
	private final static String TAG = "MyNewsActivity";
	private List<View> listViews;
	private ViewPager viewPager;
	private ViewPagerAdapter viewPagerAdapter;
	private ImageView[] dotViews;
	private int currentDotIndex = 0;
	private int msgIndex = 0;
	private boolean isclicked = false;
	private ArrayList<UnReadRIVMsg> mUnReadRIVMsgList;
	private ArrayList<UnReadSms> mUnReadSmsList;
	private ArrayList<UnReadMeetMsg> mUnReadMeetMsgList;
	private ArrayList<UnReadRingMsg> mUnReadRingMsgList;
	Map<Integer, Object> msgMap = new HashMap<Integer, Object>();
	private Animation mAnimIn;
	private View doUnreadView;
	Button leftBtn;
	Button rightBtn;
	LinearLayout dotLayout ;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_mynews);
		initUnReadData();
		// myNews details view
		initMyNewsDetailViews();
		initViewPager();

		// dots view
		initDotsViews();
		mAnimIn = AnimationUtils.loadAnimation(NewsActivity.this, R.anim.anim_down_in);
		doUnreadView = (View)findViewById(R.id.dounread_view);
		doUnreadView.setAnimation(mAnimIn);
		leftBtn = (Button)findViewById(R.id.imagebutton_left);
		rightBtn = (Button)findViewById(R.id.imagebutton_right);
		Log.d("listView_size", listViews.size()+"");
		Object object = msgMap.get(0);
		if(object instanceof UnReadSms){
			leftBtn.setBackgroundResource(R.drawable.readbutton);
			rightBtn.setBackgroundResource(R.drawable.resmsbutton);
		}else{
			leftBtn.setBackgroundResource(R.drawable.cancelbutton);
			rightBtn.setBackgroundResource(R.drawable.yesbutton);
		}
	}

	private void initViewPager() {
		viewPagerAdapter = new ViewPagerAdapter(listViews);
		viewPager = (ViewPager) findViewById(R.id.mynews_viewpager);
		viewPager.setAdapter(viewPagerAdapter);
		viewPager.setCurrentItem(1);
		viewPager.setOnPageChangeListener(this);
		
	}

	@SuppressWarnings("unchecked")
	private void initUnReadData() {
		Intent intent = getIntent();
		mUnReadRIVMsgList = (ArrayList<UnReadRIVMsg>) intent.getSerializableExtra(Constant.UNREAD_RINGIV_MSG);
		mUnReadSmsList = (ArrayList<UnReadSms>) intent.getSerializableExtra(Constant.UNREAD_SMS);
		mUnReadMeetMsgList = (ArrayList<UnReadMeetMsg>) intent.getSerializableExtra(Constant.UNREAD_MEET_MSG);
		mUnReadRingMsgList = (ArrayList<UnReadRingMsg>) intent.getSerializableExtra(Constant.UNREAD_RING_MSG);
	}

	public void goBackButton_OnClick(View v) {
		NavUtils.navigateUpFromSameTask(this);
	}

	public void mainMsgImageView_OnClick(View v) {
		Intent intent = new Intent(this, UserSettingActivity.class);
		startActivity(intent);
	}

	private void initDotsViews() {
		dotLayout = (LinearLayout) findViewById(R.id.layout_dots);
		int size = 
				mUnReadRIVMsgList.size() + 
				mUnReadSmsList.size() + mUnReadMeetMsgList.size() + mUnReadRingMsgList.size();
		dotViews = new ImageView[size];

		for (int i = 0; i < dotViews.length; i++) {
			dotViews[i] = getDotImageView(ViewsUtil.getSelector(this));
			dotViews[i].setTag(i);
			dotLayout.addView(dotViews[i]);
		}
		dotViews[currentDotIndex].setSelected(true);
	}

	private ImageView getDotImageView(StateListDrawable selector) {
		ImageView dotImageView = new ImageView(this);
		LinearLayout.LayoutParams dotLp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		dotLp.gravity = Gravity.CENTER_HORIZONTAL;
		dotImageView.setLayoutParams(dotLp);
		dotImageView.setPadding(10, 0, 10, 15);
		dotImageView.setImageDrawable(selector);
		dotImageView.setEnabled(true);
		dotImageView.setSelected(false);
		dotImageView.setClickable(true);
		dotImageView.setOnClickListener(this);
		return dotImageView;
	}

	private void initMyNewsDetailViews() {
		listViews = new ArrayList<View>();
		initUnReadSmsViews();
		initUnReadMeetMsgViews();
		initUnReadRingMsgViews();
		initUnReadRIVMsgViews();
		// null views, just for effect
		listViews.add(0, new View(this));
		listViews.add(listViews.size(), new View(this));
	}
	public void initUnReadRIVMsgViews(){
		for (int i = 0; i < mUnReadRIVMsgList.size(); i++) {
			UnReadRIVMsg unReadRIVMsg = mUnReadRIVMsgList.get(i);
			ViewGroup vg = getMyNewsDetailBackgroundView();
			addUnReadRIVMsgToBackgroundView(vg, unReadRIVMsg);
			listViews.add(vg);
			msgMap.put(msgIndex, unReadRIVMsg);
			msgIndex ++;
		}
	}
	
	//
	private void addUnReadRIVMsgToBackgroundView(ViewGroup backgroundView, UnReadRIVMsg unReadRIVMsg){
		TextView msgView = new TextView(this);
		FrameLayout.LayoutParams nicknametLp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER);
		nicknametLp.gravity = Gravity.CENTER_HORIZONTAL|Gravity.CENTER;
		msgView.setGravity(Gravity.CENTER_HORIZONTAL);
		nicknametLp.leftMargin= 30;
		nicknametLp.rightMargin = 30;
		msgView.setTextSize(20);
		msgView.setLayoutParams(nicknametLp);
		String nicknameStr = getString(R.string.unread_ring_msg);
		msgView.setText(unReadRIVMsg.getUd_nickname()+nicknameStr+unReadRIVMsg.getRing_name());
		msgView.setBackgroundResource(R.color.alpha);
		backgroundView.addView(msgView);

	}
	private void initUnReadSmsViews() {
		for (int i = 0; i < mUnReadSmsList.size(); i++) {
			UnReadSms unReadSms = mUnReadSmsList.get(i);
			ViewGroup vg = getMyNewsDetailBackgroundView();
			addUnReadSmsToBackgroundView(vg, unReadSms);
			listViews.add(vg);
			msgMap.put(msgIndex, unReadSms);
			msgIndex++;
		}

	}

	private void addUnReadSmsToBackgroundView(ViewGroup backgroundView, UnReadSms unReadSms) {
		TextView nicknameView = new TextView(this);
		FrameLayout.LayoutParams nicknametLp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL);
		nicknametLp.leftMargin = 30;
		nicknametLp.topMargin = -120;
		nicknameView.setLayoutParams(nicknametLp);
		String nicknameStr = getString(R.string.unread_sms_nickname);
		nicknameView.setText(String.format(nicknameStr, unReadSms.getSender_nickname()));
		nicknameView.setBackgroundResource(R.color.alpha);
		backgroundView.addView(nicknameView);

		TextView contentView = new TextView(this);
		FrameLayout.LayoutParams contentLp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
		contentLp.topMargin = -10;
		contentView.setLayoutParams(contentLp);
		contentView.setText(unReadSms.getSms_content());
		contentView.setBackgroundResource(R.color.alpha);
		contentView.setTextSize(20);
		backgroundView.addView(contentView);

		TextView dateView = new TextView(this);
		FrameLayout.LayoutParams dateLp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.LEFT);
		dateLp.leftMargin = 30;
		dateLp.topMargin = -85;
		dateView.setLayoutParams(dateLp);
		dateView.setText(unReadSms.getSms_date());
		dateView.setBackgroundResource(R.color.alpha);
		backgroundView.addView(dateView);
	}

	private void initUnReadMeetMsgViews() {
		for (int i = 0; i < mUnReadMeetMsgList.size(); i++) {
			UnReadMeetMsg unReadMeetMsg = mUnReadMeetMsgList.get(i);
			ViewGroup vg = getMyNewsDetailBackgroundView();
			addUnReadMeetMsgToBackgroundView(vg, unReadMeetMsg);
			listViews.add(vg);
			msgMap.put(msgIndex, unReadMeetMsg);
			msgIndex++;
		}
	}

	private void addUnReadMeetMsgToBackgroundView(ViewGroup backgroundView, UnReadMeetMsg unReadMeetMsg) {
		TextView nicknameView = new TextView(this);
		FrameLayout.LayoutParams nicknametLp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL);
		nicknametLp.leftMargin = 30;
		nicknametLp.topMargin = -120;
		nicknameView.setLayoutParams(nicknametLp);
		String nicknameStr = getString(R.string.unread_meet_nickname);
		nicknameView.setText(String.format(nicknameStr, unReadMeetMsg.getCreater_nickname()));
		nicknameView.setBackgroundResource(R.color.alpha);
		backgroundView.addView(nicknameView);

		TextView contentView = new TextView(this);
		FrameLayout.LayoutParams contentLp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
		contentLp.topMargin = -20;
		contentView.setLayoutParams(contentLp);
		contentView.setText(unReadMeetMsg.getMeet_name());
		contentView.setBackgroundResource(R.color.alpha);
		contentView.setTextSize(20);
		backgroundView.addView(contentView);

		TextView dateView = new TextView(this);
		FrameLayout.LayoutParams dateLp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
		dateLp.topMargin = 60;
		dateView.setLayoutParams(dateLp);
		String dateStr = getString(R.string.unread_meet_date);
		dateView.setText(String.format(dateStr, unReadMeetMsg.getMeet_beginDate()));
		dateView.setBackgroundResource(R.color.alpha);
		backgroundView.addView(dateView);

		TextView locationView = new TextView(this);
		FrameLayout.LayoutParams locLp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
		locLp.topMargin = 90;
		locationView.setLayoutParams(locLp);
		String locStr = getString(R.string.unread_meet_location);
		locationView.setText(String.format(locStr, unReadMeetMsg.getMg_name()));
		locationView.setBackgroundResource(R.color.alpha);
		backgroundView.addView(locationView);
	}

	private void initUnReadRingMsgViews() {
		for (int i = 0; i < mUnReadRingMsgList.size(); i++) {
			UnReadRingMsg unReadRingMsg = mUnReadRingMsgList.get(i);
			ViewGroup vg = getMyNewsDetailBackgroundView();
			addUnReadRingMsgToBackgroundView(vg, unReadRingMsg);
			listViews.add(vg);
			msgMap.put(msgIndex, unReadRingMsg);
			msgIndex++;
		}
	}

	private void addUnReadRingMsgToBackgroundView(ViewGroup backgroundView, UnReadRingMsg unReadRingMsg) {
		TextView nicknameView = new TextView(this);
		FrameLayout.LayoutParams nicknametLp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL);
		nicknametLp.leftMargin = 30;
		nicknametLp.topMargin = -120;
		nicknameView.setLayoutParams(nicknametLp);
		String nicknameStr = getString(R.string.unread_ring_creater);
		nicknameView.setText(String.format(nicknameStr, unReadRingMsg.getCreater_nickname()));
		nicknameView.setBackgroundResource(R.color.alpha);
		backgroundView.addView(nicknameView);

		TextView ringnameView = new TextView(this);
		FrameLayout.LayoutParams ringnametLp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
		ringnametLp.topMargin = -20;
		ringnameView.setLayoutParams(ringnametLp);
		String ringnameStr = getString(R.string.unread_ring_name);
		ringnameView.setText(String.format(ringnameStr, unReadRingMsg.getRing_name()));
		ringnameView.setBackgroundResource(R.color.alpha);
		ringnameView.setTextSize(20);
		backgroundView.addView(ringnameView);

		TextView contentView = new TextView(this);
		FrameLayout.LayoutParams contentLp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
		contentLp.topMargin = 55;
		contentView.setLayoutParams(contentLp);
		String introStr = unReadRingMsg.getRing_introduce();
		if (introStr != null) {
			contentView.setText(introStr);
		} else {
			contentView.setText(getString(R.string.unread_ring_nointroduce));
		}
		contentView.setBackgroundResource(R.color.alpha);
		backgroundView.addView(contentView);

	}

	private ViewGroup getMyNewsDetailBackgroundView() {
		FrameLayout layout = new FrameLayout(this);
		layout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

		ImageView backImage = new ImageView(this);
		FrameLayout.LayoutParams backLp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER);
		backImage.setLayoutParams(backLp);
		backImage.setImageResource(R.drawable.unread_msg_background);
		layout.addView(backImage);

		return layout;
	}

	public void onPageScrollStateChanged(int state) {
		
	}

	public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
		// Log.v(MyNewsActivity.class.toString(), "onPageScrolled ->" + position);
		
	}

	public void onPageSelected(final int position) {
		int selectItem =0;
		if (position == 0) {
			viewPager.setCurrentItem(position + 1);
			selectItem = position+1;
		} else if (position == listViews.size() - 1) {
			viewPager.setCurrentItem(position - 1);
			selectItem = position -1;
		}
	    Log.d(MyNewsActivity.class.toString(), "onPageSelected ->" + position);
		setCurrentDot(selectItem - 1);
		final Object object = msgMap.get(position-1);
		if(object instanceof UnReadSms){
			Log.d("Object", "UnReadSms");
			leftBtn.setBackgroundResource(R.drawable.readbutton);
			rightBtn.setBackgroundResource(R.drawable.resmsbutton);
			leftBtn.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
//					int status = doUnreadMsg(1, object, 2, null);
//					listViews.remove(position-1);
					isclicked = true;
				
				}
			});
			rightBtn.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
//					int status = doUnreadMsg(1, object, 1, null);
					isclicked = true;
				
				}
			});
			
		}else if(object instanceof UnReadMeetMsg){
			Log.d("Object", "UnReadMeetMsg");
			leftBtn.setBackgroundResource(R.drawable.cancelbutton);
			rightBtn.setBackgroundResource(R.drawable.yesbutton);
			leftBtn.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
//					int status = doUnreadMsg(2, object, 4, null);
					isclicked = true;
				
				}
			});
			
			rightBtn.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
//					int status = doUnreadMsg(2, object, 3, null);
					isclicked = true;
					
				}
			});
			
		}else if(object instanceof UnReadRingMsg){
			Log.d("Object", "UnReadRingMsg");
			leftBtn.setBackgroundResource(R.drawable.cancelbutton);
			rightBtn.setBackgroundResource(R.drawable.yesbutton);
			leftBtn.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
//					doUnreadMsg(3, object, 0, null);
					isclicked = true;
					
				}
			});
			
			rightBtn.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
//					doUnreadMsg(3, object, 2, null);
					isclicked = true;
				
				}
			});
		}else if(object instanceof UnReadRIVMsg){
			Log.d("Object", "UnReadRIVMsg");
			leftBtn.setBackgroundResource(R.drawable.cancelbutton);
			rightBtn.setBackgroundResource(R.drawable.yesbutton);
			leftBtn.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
//					doUnreadMsg(3, object, 0, null);
					isclicked = true;
				
				}
			});
			
			rightBtn.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
//					doUnreadMsg(3, object, 2, null);
					isclicked = true;
					
				}
			});
		}
		
		if (isclicked) {
			isclicked = false;
			listViews.remove(position-1);
//			msgMap.remove(position-1);
			
			viewPagerAdapter.notifyDataSetChanged();
			viewPager.setAdapter(viewPagerAdapter);
			dotViews[position-1].setSelected(false);
			dotViews[position-1] = null;
			dotLayout.removeAllViews();
			for(int i=0,j=0;i<dotViews.length; i++){
				if(dotViews[i]== null)
					continue;
				dotViews[j] = dotViews[i];
				dotViews[j].setTag(j);
				dotViews[j] = getDotImageView(ViewsUtil.getSelector(this));
				dotLayout.addView(dotViews[j++]);
			}
			
			if(selectItem < listViews.size()-2 ){
				viewPager.setCurrentItem(selectItem+1);
				currentDotIndex = selectItem;
				dotViews[currentDotIndex].setSelected(true);
		    }else if(selectItem == listViews.size()-1){
		    	if(listViews.size()>2){
		    		viewPager.setCurrentItem(1);
		    		currentDotIndex = 0;
					dotViews[currentDotIndex].setSelected(true);
		    	}
		    	else{
					NavUtils.navigateUpFromSameTask(NewsActivity.this);
				}
			}
			
		}
	}

	/*
	 * msgStyle : 1 -->UnReadSms
	 * 			  2 -->UnReadMeetMsg
	 * 			  3 -->UnReadRingMsg
	 * 			  4 -->UnReadRIVMsg
	 */
	public int doUnreadMsg(int msgStyle,Object object,int yesnoMark,String content){ 
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		int status = -1;
		int way = -1;
		try {
			
			if(msgStyle == 1){
				UnReadSms unSms = (UnReadSms)object;
				if(yesnoMark == 1){
					way = 11;
					int userId = UserInfoDAO.getUserInfo(NewsActivity.this).getUserId();
					jsonData.put("sms_send_user_id",userId);
					jsonData.put("sms_content", content);
					jsonData.put("sms_rec_user_id", unSms.getSms_send_user_id());
				}
				else{
					way = 23;
					jsonData.put("sms_id", unSms.getSms_id());
					jsonData.put("sms_state", 2);
				}
				
			}else if(msgStyle == 2){
				UnReadMeetMsg unmeetMsg = (UnReadMeetMsg)object;
				way = 24;
				jsonData.put("enl_id", unmeetMsg.getEnl_id());
				jsonData.put("enl_state", yesnoMark);
			}else if(msgStyle == 3){
				UnReadRingMsg unRingMsg = (UnReadRingMsg)object;
				way = 25;
				jsonData.put("rr_role", 2);
				jsonData.put("rr_id", unRingMsg.getRing_id());
				
			}else if(msgStyle == 4){
				UnReadRIVMsg unRivMsg = (UnReadRIVMsg)object;
				way = 25;
				jsonData.put("rr_role", 2);
				jsonData.put("rr_id", unRivMsg.getRr_id());
			}
			
			jsonResponse = JSONUtil.postRequest(way, jsonData);
			if (jsonResponse.getStatus() != Status.ERR) {
				
				JSONObject data = jsonResponse.getData();
				status = data.getInt(Constant.RESP_STATUS);
				

			}
		} catch (Exception e) {
			// TODO: handle exception

		}
		
		return status;
	}
	
	private void setCurrentDot(int dotPositon) {
		// Log.v(MyNewsActivity.class.toString(), "dotPositon ->" + dotPositon + " ,currentDotIndex -> " + currentDotIndex);
		if (dotPositon < 0 || dotPositon >= dotViews.length || currentDotIndex == dotPositon) {
			return;
		}
		// Log.v(MyNewsActivity.class.toString(), "dotPositon dot ->" + dotViews[dotPositon].isEnabled() + " ,currentDotIndex dot-> " + dotViews[currentDotIndex].isEnabled());
		dotViews[dotPositon].setSelected(true);
		dotViews[currentDotIndex].setSelected(false);

		currentDotIndex = dotPositon;
	}

	private void setCurrentView(int dotPosition) {
		if (dotPosition < 0 || dotPosition >= dotViews.length) {
			return;
		}
		
		viewPager.setCurrentItem(dotPosition + 1);
	}

	public void onClick(View v) {
		int dotPosition = (Integer) v.getTag();
		// Log.v(MyNewsActivity.class.toString(), "dotPosition ->" + dotPosition);
		setCurrentView(dotPosition);
		setCurrentDot(dotPosition);

	}
}
